package com.zcdom.framework.shiro.realm;

import com.zcdom.framework.util.ShiroUtils;
import com.zcdom.system.entity.Menu;
import com.zcdom.system.entity.Role;
import com.zcdom.system.entity.RoleMenu;
import com.zcdom.system.entity.User;
import com.zcdom.system.service.IMenuService;
import com.zcdom.system.service.IRoleMenuService;
import com.zcdom.system.service.IRoleService;
import com.zcdom.system.service.IUserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;

import javax.annotation.PostConstruct;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class UserRealm extends AuthorizingRealm {

    @Autowired
    private IUserService userService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IRoleMenuService roleMenuService;

    @Autowired
    private IMenuService menuService;


    @PostConstruct
    public void initCredentialsMatcher() {
        HashedCredentialsMatcher matcher = new HashedCredentialsMatcher("SHA-1");
        matcher.setHashIterations(1024);
        matcher.setStoredCredentialsHexEncoded(true);
        setCredentialsMatcher(matcher);
    }

    /**
     * 授权
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        User user = ShiroUtils.getUser();
        Set<String> menus=new HashSet<String>();
       SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        if (user.getRole_id()==1){
            info.addRole("admin");
            info.addStringPermission("*:*:*");
        }else {

            Role role = roleService.getById(user.getRole_id());

            List<RoleMenu> roleMenus=roleMenuService.getMenuByRoleId(role.getId());

            for (RoleMenu roleMenu:roleMenus){
                Menu menu=menuService.getMenuById(roleMenu.getMenuId());

                if (menu!=null && !StringUtils.isEmpty(menu.getPerms())){
                    menus.add(menu.getPerms());
                }

            }
            info.addRole(role.getType());
            info.setStringPermissions(menus);

        }
        return info;

    }

    /**
     * 登录认证
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;
        String username = upToken.getUsername();
        String password = "";
        if (upToken.getPassword()!=null){
            password=new String(upToken.getPassword());
        }

        User user = null;

        try{
            user = userService.selectUserByUsername(username);
        }

        catch (Exception e)
        {
            throw new AuthenticationException(e.getMessage(), e);
        }


        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user,user.getPassword(),getName());
        return  info;
    }

    /**
     * 清理缓存权限
     */
    public void clearCachedAuthorizationInfo() {
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
    }
}
